import 'package:dio/dio.dart';
import 'package:flutter_demo/env.dart';
import './CustomInterceptor.dart';
class HttpApi {
  static final BaseOptions options = BaseOptions(
      baseUrl: Env.baseUrl,
      connectTimeout: const Duration(seconds: 5), // 设置连接超时时间为 5 秒
      receiveTimeout: const Duration(seconds: 3), // 设置接收超时时间为 3 秒
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer sk-j6UX4qZnYh4j9y4"
      });

  static final dio = Dio(options);

  static Future<T> request<T>(String url,
      {String method = "get", Map<String, dynamic>? params}) async {
    // 1请求的单独配置
    final options = Options(method: method);
    // 2 添加一个拦截器
    Interceptor inter = InterceptorsWrapper(
      onRequest: (options, handler) {
        return handler.next(options);
      },
      onResponse: (e, handler) {
        print(e);
        return handler.next(e);
      },
      onError: (e, handler) {
        print(e);

        return handler.next(e);
      },
    );

    List<Interceptor> inters = [];
    inters.add(CustomInterceptor()); //添加自定义拦截器
    inters.add(LogInterceptor()); //添加内置拦截器

    dio.interceptors.addAll(inters);
    // 3 发起网络请求
    try {
      Response response = await dio.request<T>(url, queryParameters: params, options: options);
      print("测试");
      print(url);
      return response.data;
    } catch (e) {
      print(e);
      return Future.error(e);
    }
  }
}
